<?php

namespace mpend\modules\team\models;

use Yii;
use common\models\workbook\Workbook;
use common\models\workbook\WorkbookRecord;

/**
 * 班组记工本按日期统计模型
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class TeamBookDateStatsSearch extends WorkbookRecord {

    /**
     * @var string|date 开始时间
     */
    public $begin_date;

    /**
     * @var string|date 结束时间
     */
    public $end_date;

    /**
     * @inheritdoc
     */
    public function buildQuery($alias = 't') {
        $query = static::find();
        if ($alias) {
            $query->alias($alias);
            $alias .= '.';
        }
        $query->active(static::STATUS_ACTIVE);
        $query->joinWith([
            'workbook' => function($q) {
                return $q->alias('workbook')->active(Workbook::STATUS_ACTIVE);
            }
        ]);
        $query->andWhere([
            $alias . 'workbook_id' => $this->workbook_id,
            'workbook.type' => Workbook::TYPE_TEAM,
        ]);
        $this->buildDurationCondition($query, $alias . 'date');
        $query->orderBy([
            $alias . 'date' => SORT_ASC,
        ]);
        $query->debug();
        $query->groupBy([$alias . 'date']);
        $query->select([
            $alias . 'date',
            'workload' => 'sum(' . $alias . 'workload) ',
            'type' => 'sum(' . $alias . 'type)',
        ]);
        return $query;
    }

    /**
     * 查询的记工日期区间条件
     */
    public function buildDurationCondition(&$query, $field) {
        $beginDate = $this->begin_date ?: date('Y-m-d');
        $endDate = $this->end_date;
        if (!$endDate) {
            $beginDate = date('Y-m-01', strtotime($beginDate));
            $endDate = date('Y-m-d', strtotime('+1 month' . $beginDate) - 1);
        }
        $query->andFilterWhere(['between', $field, $beginDate, $endDate]);
    }

    public function fields() {
        return [
            'date',
            'type',
            'workload' => function() {
                return (float) $this->workload;
            },
        ];
    }

}
